package com.dhms.uikit.media

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.dhms.uikit.DialogBuilder
import com.dhms.uikit.R
import com.dhms.uikit.databinding.FragmentManagerBinding
import com.dhms.uikit.media.MediaActivity.Companion.BROADCAST_FILE_PATH_KEY
import com.dhms.uikit.media.MediaActivity.Companion.BROADCAST_FILE_THUMBNAIL_KEY
import com.dhms.uikit.media.MediaActivity.Companion.BROADCAST_FILE_TYPE_KEY
import com.dhms.uikit.media.MediaActivity.Companion.INTENT_FILE_LIST_KEY
import com.dhms.uikit.media.MediaActivity.Companion.INTENT_IS_PREVIEW_KEY
import com.dhms.uikit.media.MediaActivity.Companion.INTENT_TYPE_KEY
import com.dhms.uikit.media.MediaActivity.Companion.INTENT_VIEW_INDEX_KEY
import com.dhms.uikit.media.MediaActivity.Companion.SUPPORT_MEDIA_FORMAT_MAP
import java.io.File
import java.net.MalformedURLException

class ManagerFragment : Fragment() {

    private var _binding: FragmentManagerBinding? = null
    private val binding get() = _binding!!

    private var viewIndex = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val intentType = activity?.intent?.extras?.getSerializable(INTENT_TYPE_KEY)
            ?: MediaActivity.Companion.IntentType.CAPTURE
        if (intentType == MediaActivity.Companion.IntentType.CAPTURE) {
            findNavController().navigate(R.id.cameraFragment)
            return
        }

        viewIndex = activity?.intent?.extras?.getInt(INTENT_VIEW_INDEX_KEY) ?: 0
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentManagerBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = viewLifecycleOwner

        val mediaList: MutableList<MediaItem> = mutableListOf()
        val files = activity?.intent?.extras?.getStringArray(INTENT_FILE_LIST_KEY)
        files?.forEach {
            val pathList = it.split("|").toMutableList()
            var url: Uri? = null
            if (pathList.size > 0) {
                url = try {
                    Uri.parse(pathList[0])
                } catch (ex: MalformedURLException) {
                    null
                }
            }

            url?.let { u ->
                val fileExtension = File(u.path!!).extension.lowercase()
                val type = when (fileExtension) {
                    in SUPPORT_MEDIA_FORMAT_MAP[MediaType.PHOTO]!! -> MediaType.PHOTO
                    in SUPPORT_MEDIA_FORMAT_MAP[MediaType.VIDEO]!! -> MediaType.VIDEO
                    in SUPPORT_MEDIA_FORMAT_MAP[MediaType.AUDIO]!! -> MediaType.AUDIO
                    else -> return@forEach
                }
                var tmpMediaItem: MediaItem? = null
                if (type == MediaType.VIDEO) {
                    tmpMediaItem = if (pathList.size == 2) {
                        MediaItem(
                            type,
                            url,
                            Uri.parse(pathList[1])
                        )
                    } else {
                        MediaItem(
                            type,
                            url
                        )
                    }
                } else {
                    tmpMediaItem = MediaItem(
                        type,
                        url
                    )
                }

                tmpMediaItem?.let { mediaList.add(it) }
            }
        }

        binding.mediaManagerPreviewWrapper.adapter =
            ManagerViewPagerAdapter(this, mediaList)
        binding.mediaManagerPreviewWrapper.setCurrentItem(viewIndex, false)
        binding.currentMediaIndex = viewIndex + 1
        binding.mediaCount = mediaList.size

        binding.mediaManagerPreviewWrapper.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)

                binding.currentMediaIndex = position + 1
            }
        })

        binding.toolNavIcon.setOnClickListener {
            (activity as MediaActivity).finishActivity()
        }

        if (activity?.intent?.extras?.getBoolean(INTENT_IS_PREVIEW_KEY) == false) {
            val deleteConfirmDialog =
                DialogBuilder(requireContext()).setTitle(getString(R.string.delete_media_config))
                    .setOnPositiveButtonClickListener {
                        val currentMediaIndex = binding.currentMediaIndex - 1
                        val currentMedia = mediaList[binding.currentMediaIndex - 1]
                        val intent =
                            Intent(MediaActivity.BROADCAST_DELETE_ACTION + (activity as MediaActivity).viewId)
                        intent.putExtra(BROADCAST_FILE_PATH_KEY, currentMedia.file)
                        intent.putExtra(BROADCAST_FILE_TYPE_KEY, currentMedia.type)
                        intent.putExtra(BROADCAST_FILE_THUMBNAIL_KEY, currentMedia.thumbnail)
                        activity?.sendBroadcast(intent)

                        val oldMediaListSize = mediaList.size
                        if (oldMediaListSize == 1) {
                            (activity as MediaActivity).finishActivity()
                        } else {
                            if (binding.currentMediaIndex == oldMediaListSize) {
                                binding.mediaManagerPreviewWrapper.setCurrentItem(
                                    binding.currentMediaIndex - 2,
                                    true
                                )
                            }
                            (binding.mediaManagerPreviewWrapper.adapter as ManagerViewPagerAdapter).removeFragment(
                                currentMediaIndex
                            )
                            binding.mediaCount = mediaList.size
                        }
                        true
                    }.setOnNegativeButtonClickListener().createDialog()
            binding.toolOptionIcon.setOnClickListener {
                deleteConfirmDialog.show()
            }
        } else {
            binding.toolOptionIcon.visibility = View.GONE
        }
    }

    companion object {
        const val TAG = "ManagerFragment"

        private val FILE_NAME_REGEX =
            """^(\d){4}(-(\d){2}){2}_((\d){2}-){2}(\d){2}\.\S+$""".toRegex()
    }
}